<script setup lang="ts">
import { computed, onUnmounted, onMounted, shallowRef } from 'vue'

type Props = {
  modelValue: string
  promote: (s: string) => string[] | null | undefined
  placeholder?: string
}
const props = withDefaults(defineProps<Props>(), {
  promote: (s: string) => null
})

const promote = shallowRef<string[] | null | undefined>(null)

const emits = defineEmits<{
  (e: 'update:modelValue', v: string): void
}>()

const value = computed({
  get() {
    return props.modelValue
  },
  set(v: string) {
    emits('update:modelValue', v)
  }
})

function onInput(evt: Event) {
  let s = (evt.target as HTMLInputElement).value
  if (!s) {
    promote.value = null
    return
  }
  s = s.trim()
  if (s.length === 0) {
    promote.value = null
    return
  }
  promote.value = props.promote(s)
}

function clickPromote(s: string) {
  emits('update:modelValue', s)
  promote.value = null
}

function onClick() {
  promote.value = null
}

onMounted(() => {
  document.addEventListener('mousedown', onClick, true)
})

onUnmounted(() => {
  document.removeEventListener('mousedown', onClick, true)
})
</script>
<template>
  <div class="promote-input">
    <input class="input" :placeholder="placeholder || ''" v-model="value" @input="onInput" />
    <div class="promote-list-wrap">
      <div class="promote-list" v-if="promote && promote.length > 0">
        <div class="promote-entry" v-for="p in promote" @mousedown="clickPromote(p)">
          {{ p }}
        </div>
      </div>
    </div>
  </div>
</template>
